﻿using Grow.Domain.Object;
using Grow.Domain.Repository.CreateDomainRepository;
using Grow.Module.Options;
using Grow.Module.Service;
using Microsoft.Extensions.DependencyInjection;

namespace Grow.Domain.Repository.EntityFrameworkCore.SqlServer.CreateDomainRepository
{
    public class CreateDomainRepositoryBuilder : ICreateDomainRepositoryBuilder
    {
        private readonly List<IDbMap> _tableMaps;
        private readonly IServiceContainer _serviceContainer;
        public CreateDomainRepositoryBuilder(IServiceContainer serviceContainer)
        {
            _tableMaps = new();
            _serviceContainer = serviceContainer;
        }

        public ICreateDomainRepositoryBuilder AddUnitOfWork(Action<IOptionsBind, UnitOfWorkOptions> dbOptionsAction)
        {
            _serviceContainer.OptionsManager.AddOptions<UnitOfWorkOptions>(a =>
            {
                dbOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });

            return this;
        }

        public ICreateDomainRepositoryBuilder AddDomainRepository<TDomainRepositoryService, TDomainRepositoryImplementation, TAggregateRoot>()
           where TDomainRepositoryService : class, IDomainRepository<TAggregateRoot>
           where TDomainRepositoryImplementation : class, TDomainRepositoryService
           where TAggregateRoot : class, IAggregateRoot
        {
            _ = _serviceContainer.ServiceCollection.AddScoped<TDomainRepositoryService, TDomainRepositoryImplementation>();
            return this;
        }

        public ICreateDomainRepositoryBuilder AddDbMap<TTableMap>() where TTableMap : IDbMap, new()
        {
            TTableMap tableMap = new();
            if (!_tableMaps.Contains(tableMap))
            {
                _tableMaps.Add(tableMap);
            }
            return this;
        }
        public IEnumerable<IDbMap> GetTableMaps()
        {
            return _tableMaps;
        }

    }
}
